package com.kfm.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.kfm.common.domain.entity.Orders;
import com.kfm.common.util.QRCodeUtil;
import com.kfm.order.config.StoreAlipayConfig;
import com.kfm.order.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.Map;

@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {

    @Resource
    private StoreAlipayConfig storeAlipayConfig;

    @Override
    public byte[] alipay(Orders orders) throws Exception {
        return pay(orders);
    }

    private byte[] pay(Orders orders) throws Exception {
        // 实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(getConfig());
        // 创建请求参数对象
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        // 模拟数据
        model.setOutTradeNo(orders.getOrderId());
        model.setTotalAmount(String.valueOf(orders.getTotalAmount()));
        model.setSubject("开发喵商城");
        // 创建API对应的request类
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        // 设置异步回调 url
        request.setNotifyUrl(storeAlipayConfig.getNotifyUrl());
        request.setBizModel(model);
        AlipayTradePrecreateResponse response = alipayClient.execute(request);

        // 解析响应结果
        if (response.isSuccess()) {
            System.out.println("请求成功");
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            QRCodeUtil.generateQRCode(response.getQrCode(), outputStream);
            return outputStream.toByteArray();
        }
        log.error("创建失败{}", response.getMsg());
        return null;
    }

    /**
     * 生成一个支付宝配置对象，设置配置参数并返回该对象。
     *
     * @return 支付宝配置对象
     */
    private AlipayConfig getConfig() {
        // 创建支付宝配置对象
        AlipayConfig alipayConfig = new AlipayConfig();
        // 设置网关地址
        alipayConfig.setServerUrl(storeAlipayConfig.getUrl());
        // 设置应用ID
        alipayConfig.setAppId(storeAlipayConfig.getAppid());
        // 设置应用私钥
        alipayConfig.setPrivateKey(storeAlipayConfig.getPrivateKey());
        // 设置请求格式，固定值为json
        alipayConfig.setFormat(storeAlipayConfig.getFormat());
        // 设置字符集
        alipayConfig.setCharset(storeAlipayConfig.getCharset());
        // 设置签名类型
        alipayConfig.setSignType(storeAlipayConfig.getSignType());
        // 设置支付宝公钥
        alipayConfig.setAlipayPublicKey(storeAlipayConfig.getAlipayPublicKey());
        // 返回支付宝配置对象
        return alipayConfig;
    }


    @Override
    public Boolean alipayCallback(Map<String, String> request) {
        try {
            log.info("回调参数{}", request);
            String trade_no = request.get("trade_no"); // 获取交易的流水号
            String body1 = request.get("body"); // 获取交易信息
            log.info("交易的流水号和交易信息{}, {}", trade_no, body1);
            JSONObject body = JSONObject.parseObject(body1); // 将交易信息解析为JSON对象
            String payType = body.getString("payType"); // 获取支付类型
            String orderNumber = body.getString("orderNumber"); // 获取订单号
            if (payType != null && payType.equals("1")) { // 判断支付类型是否为1
                // TODO 修改订单的状态
                // payCommonService.payproductcourse(body, "1", orderNumber, trade_no, "1");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异常{}", e.getMessage());
            return false;
        }
        return true;
    }

}
